//
//  LBCountryFilter.mm
//  OpenGLGame
//
//  Created by Nguyen Cong Huy on 1/22/13.
//  Copyright (c) 2013 UIT. All rights reserved.
//

#include "LBCountryFilter.h"

char newCountryFilterFragStr[] = ""

"precision mediump float;"

"varying vec2 vtexCoor;"
"uniform sampler2D texture;"


// exposure function
"vec4 exposure(vec4 color, float expo){"
"   vec4 result = vec4(color.rgb * pow(2.0, expo), color.a);"
"   return result;"
"}"
// END exposure function

//contrast function (default 1.0)
"vec4 contrastColor(vec4 color, float contrast){"
"   color.r = (color.r - 0.5)*contrast + 0.5;"
"   color.g = (color.g - 0.5)*contrast + 0.5;"
"   color.b = (color.b - 0.5)*contrast + 0.5;"
"   color = clamp(color, 0.0, 1.0);"
"   return color;"
"}"
//END contrast function

//function colorOffset
"vec4 colorOffset(vec4 color, vec4 offset){"
"   color = color + offset;"
"   return color;"
"}"
// END function colorOffset

// function whiteBalance
"vec4 whiteBalance(vec4 color, float temperature, float tint){"
"   const mediump mat3 RGBtoYIQ = mat3(0.299, 0.587, 0.114, 0.596, -0.274, -0.322, 0.212, -0.523, 0.311);"
"   const mediump mat3 YIQtoRGB = mat3(1.0, 0.956, 0.621, 1.0, -0.272, -0.647, 1.0, -1.105, 1.702);"
"   const mediump vec3 warmFilter = vec3(0.93, 0.54, 0.0);"

"   if(temperature < 5000.0) temperature = 0.0004 * (temperature - 5000.0);"
"   else temperature = 0.00006 * (temperature - 5000.0);"

"	mediump vec3 yiq = RGBtoYIQ * color.rgb;"
"	yiq.b = clamp(yiq.b + tint*0.5226*0.1, -0.5226, 0.5226);"
"	lowp vec3 rgb = YIQtoRGB * yiq;"

"	vec3 processed = vec3("
"                              (rgb.r < 0.5 ? (2.0 * rgb.r * warmFilter.r) : (1.0 - 2.0 * (1.0 - rgb.r) * (1.0 - warmFilter.r))), "
"                              (rgb.g < 0.5 ? (2.0 * rgb.g * warmFilter.g) : (1.0 - 2.0 * (1.0 - rgb.g) * (1.0 - warmFilter.g))), "
"                              (rgb.b < 0.5 ? (2.0 * rgb.b * warmFilter.b) : (1.0 - 2.0 * (1.0 - rgb.b) * (1.0 - warmFilter.b))));"


"    vec4 result = vec4(mix(rgb, processed, temperature), color.a);"
"    return result;"
"}"
// END function whiteBalance


"void main()"
"{"
"   lowp vec4 textureColor = texture2D(texture, vtexCoor);"
"   vec4 result = textureColor;"

"   result = colorOffset(result, vec4(0.1, 0.03, 0.0, 0.0));"
"   result = whiteBalance(result, 5500.0, 0.0);"
"   result = contrastColor(result, 1.2);"
"   result = exposure(result, 0.05);"

"   gl_FragColor = result;"
"}";

LBCountryFilter::LBCountryFilter(){
    init(0, newCountryFilterFragStr);
}